﻿/**
 * @Description 基础框架服务调用实例-数据服务-语法参数
 *@Author  guoyanfei
 */
var preUrl = "/gdp";
var businessServiceUrl = ""
var input_paramDict = new Map();
input_paramDict.set('serviceID', 'input_serviceId')
input_paramDict.set('pageNO','input_pageNO')
input_paramDict.set('pageSize', 'input_pageSize');
input_paramDict.set('appCode', 'input_appCode');

var postPath = '/gdp'
var serviceUrl = '/gdp'


var commServices = commServices || {};
commServices.prototype = {
    init: function () {//表格初始化
        commServices.prototype.setSearchColumn();
        commServices.prototype.IsPage();
        commServices.prototype.eventSearch();

        commServices.prototype.eventExecuteBusinessService();
        // here is get all dynamic condition and set condition html
        commServices.prototype.handleDynamicConditionParameter();
//        commServices.prototype.getFieldConditionTable();

        getFieldList();
        getFieldConditionList();

    },
    IsPage:function(){
        var ispage = true;
        $.ajax({
            url: postPath + '/business/multipleServer/selectIsPaging',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            success: function (data) {
                ispage = data;
                isPageFormat = ispage;

            },
            error: function () {
                bootbox.alert("查询是否分页失败!");
            }
        });
        if (ispage) {
            commServices.prototype.createPageTable();
        } else {
            commServices.prototype.createTable();
        }
    },
    createTable: function () {//不分页表格初始化
        $("#tb_list").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/business/multipleServer/multipleTableServer',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色  
            cache: false, // 是否使用缓存
            showColumns: true,
            showRefresh: true,
            responseHandler: function (res) {
                return handleResponseResult(res);
            },
            queryParams: {
                serviceID: serviceId, conQuery: commServices.prototype.setSearchParams,
                from: 'ADMIN'
            },
            uniqueId: "guid", // 每一行的唯一标识 
            columns: commServices.prototype.getTableColumn()
  
        });
    },
    createPageTable:function(){//分页表格初始化
        $("#tb_list").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/business/multipleServer/multipleTableServer',
            undefinedText: '-',
            method: 'get',
            pagination: true,
            striped: true,
            cache: false,
            pageList: [5, 10, 20],
            toolbar: "#toolbar",
            showColumns: true,
            showRefresh: true,
            sidePagination: "server",
            responseHandler:function(res){
                return handleResponseResult(res);
            },
            queryParams: commServices.prototype.queryParams,
            uniqueId:'guid',
            columns: commServices.prototype.getTableColumn()
        });
    },
    queryParams: function (pageReqeust) {//表格参数设置
        var temp = {
            serviceID: serviceId,
            pageNO: pageReqeust.offset / pageReqeust.limit + 1,
            pageSize: pageReqeust.limit,
            conQuery: commServices.prototype.setSearchParams(),
            from: 'ADMIN'
        };
        return temp;
    },
    getTableColumn: function () {//设置表格显示列
        var columns = [];
        columns.push({ field: 'state', checkbox: true, align: 'center', valign: 'middle' });
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/multipleServer/selectShowFiled',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {

                columnData = data.data;
            },
            error: function () {
                bootbox.alert("显示列数据加载失败!");
            }
        });
        $.each(columnData, function (i, e) {
            columns.push({ "field": e.fieldname, "title": e.fieldnamecn, "align": 'center', "valign": 'middle' });
        });
        return columns;
    },
    setSearchColumn: function () {//设置查询列
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/multipleServer/selectQueryFiled',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                bootbox.alert("列数据加载失败!");
            }
        });
        if (columnData != null) {
            $.each(columnData, function (i, e) {
                switch (e.showtype) {
                    case "0"://文本框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='search_" + e.fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='search_" + e.fieldname + "' placeholder='请输入" + e.fieldnamecn + "' type='text' class='form-control' >");
                        break;
                    case "1"://下拉框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='search_" + e.fieldname + "'>" + e.fieldnamecn + "：</label>");
                        var strtxt = "<select id='search_" + e.fieldname + "'  class='form-control' >"
                                       + "<option value=''>请选择</option>";
                        if (e.enumvalue != null && e.enumvalue != "") {
                            var enums = e.enumvalue.split(',');
                            for (var i = 0; i < enums.length; i++) {
                                var eb = enums[i].split(':');
                                strtxt += "<option value='" + eb[0] + "'>" + eb[1] + "</option>";
                            }
                        }
                        strtxt += "</select>";
                        $("#txtSearch").append(strtxt);
                        break;
                    case "4"://日期框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='search_" + e.fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='search_" + e.fieldname + "' data-date-format=\"yyyy-mm-dd HH:mm:ss\" type='text' class='form-control' >");
                        $("#search_" + e.fieldname + "").datetimepicker({
                            language: 'zh-CN',
                            autoclose:true,
                            autoUpdateInput: true
                        });
                        break;
                }
            });

        }
    },
    setSearchParams: function () {//设置查询参数
        var searchParams ="";
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/multipleServer/selectQueryFiled',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                bootbox.alert("列数据加载失败!");
            }
        });
        if (columnData != null) {
            var strcon = "=";
            $.each(columnData, function (i, e) {
                if ($('#search_' + e.fieldname).val() != null && $('#search_' + e.fieldname).val() != 'undefined' && $('#search_' + e.fieldname).val() != "") {
                    if (searchParams == "") {
                        searchParams = "\"" + e.fieldname + "\":\""+ $('#search_' + e.fieldname).val()+"\"";
                    } else { 
                        searchParams += ",\"" + e.fieldname + "\":\"" + $('#search_' + e.fieldname).val() + "\"";
                    }
                }
            });

            searchParams = "{" + searchParams + "}";
        }
        return searchParams;
    },
    eventSearch: function () {//查询操作
        $("#btn_search").click(function () {
            $("#tb_list").bootstrapTable('refresh');
        });
    },
    handleDynamicConditionParameter :function(){//查询操作
        console.log("luowen execute handleDynamicConditionParameter ")
        // here is get all condition item
        // http://localhost:9000/system/queryfield/getQueryFieldList?serviceId=localhost_GDP_singleTable_AIOV&serviceType=1&grade=&paramType=1
        var url = preUrl + '/system/server/selectAllFiled';

        // here assgin value to serviceId
        $("#input_serviceId").val(serviceId);

        console.log("luowen serviceID", serviceId)
        $.ajax({
            url: url,
            type: 'GET',
            data: {"sysId": serviceId},
            success: function(data){
                if(data == null)
                    return;

                var appendHtml = "";
                data.forEach(function(e, i){
                    // create html object
                    console.log("luowen element", e);
                    //return;
                    var trObject = "<tr>";
                    trObject += "<td>" + e.parametercode + "</td>";
                    trObject += "<td>" + e.fieldJavaType+ "</td>";
                    trObject += "<td>" + e.note + "</td>";
                    trObject += "<td>" + "<input type='text' style='width:100%' id=input_"+e.parametercode + " value = ''/> " + "</td>";
                    trObject += "</tr>"
                    // append
                    appendHtml += trObject;
                    input_paramDict.set(e.parametercode , "input_" + e.parametercode);
                });

                console.log("luowen appendHtml object", appendHtml)
                console.log("luowen input_paramDict", input_paramDict)
                $("#inputParameterList").append(appendHtml);
                // here is save input_param_
            },
            error: function(data){
                console.log("luowen fail dynamic condition parameter",data)
            }

        });

    },
    eventExecuteBusinessService:function(){//查询操作
        $("#btn_executeBusinessService").click(function () {
            // here is logic to expression all content
            // first section handle param
            // get general parameter
            var input_serviceId = $("#input_serviceId").val();
            var input_pageNO = $("#input_pageNO").val();
            var input_pageSize = $("#input_pageSize").val();
            console.log("luowen general input parameter", input_serviceId, input_pageNO, input_pageSize)
            $.ajax({
                url: preUrl + "/business/multipleServer/multipleTableServer",
                type: 'GET',
                data: getUrlInputParameter(),
                success: function(data){
                    console.log("luowen success execute response request", data)
                    generateCompleteUrl();
                    format_JS_code();
                    displayJsCodeResponse(data);

                },
                error: function(data){
                    console.log("luowen fail execute response request", data)

                }
            });
        });
    },






};

function queryFieldParaming(pageReqeust) {
    var sid = $("#serverId").val();
    var temp = {
        order: pageReqeust.order,
        sysId: sid
    };
    console.log("luowen queryFieldParaming ", temp);
    return temp;
}




//服务初始化
$(function () {
    $('#sp_seviceUrl').append("服务地址：" + postPath + "/business/multipleServer/multipleTableServer");
    $('#sp_seviceUrl').append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务ID：" + serviceId);

    preUrl = postPath
    businessServiceUrl = preUrl + "/business/multipleServer/multipleTableServer";

    $('.s_id').text(serviceId);
    var comm = commServices.prototype;
    comm.init();
})

function getParameterValue(key){
    var value = getUrlInputParameter[key]
    console.log("luowen key value", key, value)
}

function getUrlInputParameter(){
    // here is build those object
    var inputParameter = {};
    input_paramDict.forEach((value, key) => {
        var inputValue = $("#" + value).val();
        if(inputValue == null || inputValue == undefined){
            inputValue = '';
        }
        var id = "#"+value;
        console.log("luowen map value", value, key, $(id).val(), id, inputValue)

        inputParameter[key] = inputValue
    });

    console.log("luowen final answer url parameter", inputParameter);
    return inputParameter;
}


function generateCompleteUrl(){
    var completeUrl = businessServiceUrl + "?"
    var formatParameter = getUrlInputParameter();
    console.log("luowen formatParameter", formatParameter)

    Object.keys(formatParameter).forEach( key => {
        completeUrl += "&" + key + "=" + formatParameter[key];
    })

//    var encodeUrl = encode_utf8(completeUrl);
    var encodeUrl = completeUrl;

    console.log("luowen encodeUrl", encodeUrl);
    $("#completeUrl").html(encodeUrl);
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}

function format_JS_code(){
    var url = businessServiceUrl;
    var dataString = JSON.stringify(getUrlInputParameter());
    console.log("luowen dataString", dataString);

    var jsCode = "";
    jsCode += "\r\n$.ajax({";
    jsCode += "\r\n      url: " + url + ", ";
    jsCode += "\r\n      type: 'GET', ";
    jsCode += "\r\n      data: " + dataString + ", ";
    jsCode += "\r\n      success: function(responseData){" ;
    jsCode += "\r\n      }";
    jsCode += "\r\n})";

    console.log("luowen jsCode", jsCode)
    $("#generateJsCode").html(jsCode)
}

function displayJsCodeResponse(responseData){
    if(responseData == null)
        return;
    var responseContent = JSON.stringify(responseData, null, 2)
    console.log("luowen responseContent", responseContent)
    $("#displayJsCodeResponse").text(responseContent);
}


function getFieldList() {
    $("#tb_field").bootstrapTable({
        url: preUrl + '/system/server/selectServerColumn',
        type: 'GET',
        undefinedText: '-',
        striped: true, // 是否显示行间隔色
        queryParams: {'sysId' : serviceId},
        cache: false, // 是否使用缓存
        uniqueId: "guid", // 每一行的唯一标识
        columns: [{
            title: '字段名称',
            field: 'filedname',
            align: 'center',
            valign: 'middle'
        }, {
            title: '中文名称',
            field: 'fieldcaption',
            align: 'center',
            valign: 'middle'
        }]
    });
}

function getFieldConditionList() {

    var url = preUrl + '/system/server/selectAllFiled';


    console.log("luowen serviceID and url ", serviceId, url)
        $.ajax({
            url: url,
            type: 'GET',
            data: {"sysId": serviceId},
            success: function(data){
                if(data == null)
                    return;

                var appendHtml = "";
                data.forEach(function(e, i){
                    // create html object
                    console.log("luowen element", e);
                    //return;
                    var trObject = "<tr>";
                    trObject += "<td>" + e.parametercode + "</td>";
                    trObject += "<td>" + e.fieldJavaType+ "</td>";
                    trObject += "<td>" + e.note + "</td>";
                    trObject += "<td>" + "<input type='text' style='width:100%' id=input_"+e.parametercode + " value = ''/> " + "</td>";
                    trObject += "</tr>"
                    // append
                    appendHtml += trObject;
                    input_paramDict.set(e.parametercode , "input_" + e.parametercode);
                });

                console.log("luowen appendHtml object", appendHtml)
                console.log("luowen input_paramDict", input_paramDict)
                $("#inputParameterList").append(appendHtml);
                // here is save input_param_
            },
            error: function(data){
                console.log("luowen fail dynamic condition parameter",data)
            }

        });


}

function  getFieldConditionList() {
    $("#tb_fieldCondition").bootstrapTable({
        url: preUrl + '/system/server/selectAllFiled',
        undefinedText: '-',
        striped: true, // 是否显示行间隔色
        queryParams: {'sysId': serviceId},
        cache: false, // 是否使用缓存
        uniqueId: "guid", // 每一行的唯一标识
        columns: [{
            title: '字段名称',
            field: 'parametercode',
            align: 'center',
            valign: 'middle',
        },{
            title: '中文名称',
            field: 'note',
            align: 'center',
            valign: 'middle'
        }, {
            title: 'Java类型',
            field: 'fieldJavaType',
            align: 'center',
            valign: 'middle',

        }]

    });
}
